package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.config.RabbitMQConfig;
import com.hmdp.dto.Result;
import com.hmdp.dto.VoucherOrderMessageDTO;
import com.hmdp.entity.SeckillVoucher;
import com.hmdp.entity.VoucherOrder;
import com.hmdp.mapper.VoucherOrderMapper;
import com.hmdp.service.ISeckillVoucherService;
import com.hmdp.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisIdWorker;
import com.hmdp.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.data.redis.connection.stream.*;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedisIdWorker redisIdWorker;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    private VoucherOrderServiceImpl voucherOrderService;

    private static final DefaultRedisScript<Long> defaultRedisScript;
    static {
        defaultRedisScript = new DefaultRedisScript<>();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setLocation(new ClassPathResource("seckill.lua"));
    }


    // 单线程池
    private static final ExecutorService executorService = Executors.newSingleThreadExecutor();

    @PostConstruct
    public void init(){
        executorService.submit(new VoucherOrderHandler());
    }

    // 消息队列任务类
    private class VoucherOrderHandler implements Runnable{
        private String queueName = "stream.orders";
        @Override
        public void run() {
            while (true){
                try {
                    // 获取消息队列中订单信息 xreadgroup group g1【组】 c1【消费者】 count 1 block 2000 streams stream.order >
                    List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(Consumer.from("g1", "c1"),
                            StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
                            StreamOffset.create(queueName, ReadOffset.lastConsumed()));
                    // 判断队列中是否有消息
                    if (CollectionUtil.isEmpty(list)){
                        // 没有消息就继续等待
                        continue;
                    }
                    MapRecord<String, Object, Object> record = list.get(0);
                    Map<Object, Object> value = record.getValue();
                    VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                    // 获取成功，下单
                    handleVoucherOrder(voucherOrder);
                    // 确认消息
                    stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                } catch (Exception e) {
                    log.error("处理订单异常", e);
                    // 处理有异常的订单，异常的消息会进入pending-list，不会被ack
                    // 继续从pending-list中获取
                    while(true){
                      try {
                          // 获取消息队列中订单信息 xreadgroup group g1【组】 c1【消费者】 count 1 streams stream.order 0
                          List<MapRecord<String, Object, Object>> list = stringRedisTemplate.opsForStream().read(
                                  Consumer.from("g1", "c1"),
                                  StreamReadOptions.empty().count(1),
                                  StreamOffset.create(queueName, ReadOffset.from("0")));
                          // 判断队列中是否有消息
                          if (CollectionUtil.isEmpty(list)){
                              // 说明pending-list没有异常消息，结束循环
                              break;
                          }
                          MapRecord<String, Object, Object> record = list.get(0);
                          Map<Object, Object> value = record.getValue();
                          VoucherOrder voucherOrder = BeanUtil.fillBeanWithMap(value, new VoucherOrder(), true);
                          // 获取成功，下单
                          handleVoucherOrder(voucherOrder);
                          // 确认消息
                          stringRedisTemplate.opsForStream().acknowledge(queueName, "g1", record.getId());
                      } catch (Exception ex){
                          log.error("处理pending-list订单异常", e);
                          try {
                              // 继续不断循环获取异常信息，休眠20ms
                              Thread.sleep(20);
                          } catch (InterruptedException interruptedException) {
                              interruptedException.printStackTrace();
                          }
                      }
                    }

                }
            }
        }
    }

//    // 阻塞队列
//    private BlockingQueue<VoucherOrder> orderTasks = new ArrayBlockingQueue<>(1024 * 1024);
//    // 阻塞队列任务处理类
//    private class VoucherOrderHandler implements Runnable{
//        @Override
//        public void run() {
//            while (true){
//                try {
//                    // 有元素才有继续向下执行，否则一直陷入阻塞状态
//                    // 感觉类似于监听器的作用：有元素就执行否则跳过
//                    VoucherOrder voucherOrder = orderTasks.take();
//                    handleVoucherOrder(voucherOrder);
//                } catch (InterruptedException e) {
//                    log.error("处理订单异常", e);
//                }
//
//            }
//        }
//    }

    private void handleVoucherOrder(VoucherOrder voucherOrder) {
        // 这里不能用UserHolder来获取用户的信息，因为这里的线程是子线程，不是父线程
        Long userId = voucherOrder.getUserId();
        RLock lock = redissonClient.getLock("lock:order:" + userId);
        Boolean aBoolean = lock.tryLock();
        if (!aBoolean){
            log.error("请勿重复下单");
            return;
        }
        try {
            voucherOrderService.getResultEasy(voucherOrder);
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        Long userId = UserHolder.getUser().getId();
        // 赋值全局变量
        voucherOrderService = (VoucherOrderServiceImpl) AopContext.currentProxy();
        Long orderId = redisIdWorker.nextId("order");

        // 使用Lua脚本
        Long result = stringRedisTemplate.execute(defaultRedisScript, Collections.emptyList(), voucherId.toString(), userId.toString(), orderId.toString());
        if (!result.equals(0L)){
            return Result.fail(result.equals(1L) ? "库存不足": "请勿重复下单");
        }

        return Result.ok(orderId);
    }

    // 阻塞队列版本
//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        Long userId = UserHolder.getUser().getId();
//        // 使用Lua脚本
//        Long result = stringRedisTemplate.execute(defaultRedisScript, Collections.emptyList(), voucherId.toString(), userId.toString());
//        if (!result.equals(0L)){
//            return Result.fail(result.equals(1L) ? "库存不足": "请勿重复下单");
//        }
//        // 创建订单
//        Long orderId = redisIdWorker.nextId("order");
//        VoucherOrder voucherOrder = new VoucherOrder();
//        voucherOrder.setId(orderId);
//        voucherOrder.setUserId(userId);
//        voucherOrder.setVoucherId(voucherId);
//        // 赋值全局变量
//        voucherOrderService = (VoucherOrderServiceImpl) AopContext.currentProxy();
//        // 添加到阻塞队列中
//        orderTasks.add(voucherOrder);
//
//        return Result.ok(orderId);
//    }


//    @Override
//    public Result seckillVoucher(Long voucherId) {
//        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucherId);
//        // 判断时间是否在有效期内
//        LocalDateTime now = LocalDateTime.now();
//        if (now.isAfter(seckillVoucher.getEndTime())){
//            return Result.fail("秒杀已结束");
//        }
//        if (now.isBefore(seckillVoucher.getBeginTime())){
//            return Result.fail("秒杀尚未开始");
//        }
//
//        // 扣减库存
//        if (seckillVoucher.getStock() < 1){
//            return Result.fail("库存不足");
//        }
//
//        // 使用悲观锁，限制一人一单
//        Long userId = UserHolder.getUser().getId();
//
//        // 单机模式下
////        synchronized (userId.toString().intern()){
////            // 使用代理对象，能够处理事务
////            VoucherOrderServiceImpl voucherOrderService = (VoucherOrderServiceImpl) AopContext.currentProxy();
////            return voucherOrderService.getResult(voucherId, userId);
////        }
//
//        // 集群模式下
//        // 使用自己创建的锁
////        SimpleRedisLock simpleRedisLock = new SimpleRedisLock("order:" + userId, stringRedisTemplate);
////        Boolean aBoolean = simpleRedisLock.tryLock(10L);
//        // 使用redisson
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        Boolean aBoolean = lock.tryLock();
//        if (!aBoolean){
//            return Result.fail("请勿重复下单");
//        }
//        try {
//            VoucherOrderServiceImpl voucherOrderService = (VoucherOrderServiceImpl) AopContext.currentProxy();
//            return voucherOrderService.getResult(voucherId, userId);
//        } catch (Exception e){
//            e.printStackTrace();
//        } finally {
////            simpleRedisLock.unLock();
//            lock.unlock();
//
//        }
//
//        return Result.ok();
//    }

    @Transactional
    public Result getResult(Long voucherId, Long userId) {
        // 判断是否已经购买过了
        Integer integer = this.baseMapper.selectCount(new QueryWrapper<VoucherOrder>().eq("user_id", userId).eq("voucher_id", voucherId));
        if (integer > 0){
            return Result.fail("用户已经购买过了");
        }

        // 扣减库存
        boolean flag = seckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0) // 关键步骤，使用乐观锁的CAS法
                .update();
        if (!flag){
            return Result.fail("库存不足");
        }

        // 保存订单
        // RabbitMQ方法
//        rabbitTemplate.convertAndSend(RabbitMQConfig.MSG_QUEUE, new VoucherOrderMessageDTO(userId, voucherId));

        Long orderId = redisIdWorker.nextId("order");
        VoucherOrder voucherOrder = new VoucherOrder();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(userId);
        voucherOrder.setVoucherId(voucherId);
        this.baseMapper.insert(voucherOrder);
        return Result.ok();
    }


    // 秒杀优化版本
    @Override
    @Transactional
    public void getResultEasy(VoucherOrder voucherOrder) {
        // 判断是否已经购买过了
        Long userId = voucherOrder.getUserId();
        Long voucherId = voucherOrder.getVoucherId();
        Integer integer = this.baseMapper.selectCount(new QueryWrapper<VoucherOrder>().eq("user_id", userId)
                                                                                .eq("voucher_id", voucherId));
        if (integer > 0){
            log.error("用户已经购买过了");
            return;
        }

        // 扣减库存
        boolean flag = seckillVoucherService.update().setSql("stock = stock - 1")
                .eq("voucher_id", voucherId)
                .gt("stock", 0) // 关键步骤，使用乐观锁的CAS法
                .update();
        if (!flag){
            log.error("库存不足");
            return;
        }

        this.baseMapper.insert(voucherOrder);
    }
}
